import 'dart:async';
import 'dart:io';
import 'dart:ui';

import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:adaptive_theme/adaptive_theme.dart';
import 'package:appscheme/appscheme.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_plugin_engagelab/flutter_plugin_engagelab.dart';
// import 'package:flutter_apns/apns.dart';
// import 'package:flutter_apns/flutter_apns.dart';
// import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/utils/lc_event_bus/call.dart';
import 'package:smart_freezer/core/utils/lc_event_bus/notify.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:ty_smart_home/ty_smart_home.dart';
// import 'package:month_year_picker/month_year_picker.dart';

import 'core/resources/app_config.dart';
import 'core/resources/routers.dart';
import 'core/service/api/app_api.dart';
import 'core/service/service/result_data.dart';
import 'core/utils/color_util.dart';
import 'core/utils/local_storage.dart';
import 'generated/codegen_loader.g.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化存储工具
  await SpUtil.getInstance();
  await EasyLocalization.ensureInitialized();

  // 捕获全局异常
  runZonedGuarded((){
    ErrorWidget.builder = (FlutterErrorDetails details) {
      Zone.current.handleUncaughtError(details.exception, details.stack!);

      final size = MediaQueryData.fromWindow(WidgetsBinding.instance.window).size;

      return Container(
        width: size.width,
        height: size.height,
        color: Colors.grey.shade100.withOpacity(0.5),
        padding: EdgeInsets.fromLTRB(10, 30, 10, 20),
        child: SingleChildScrollView(child: Text(details.exception.toString() + "\n\n " + details.stack.toString(), style: TextStyle(color: Colors.black),)),
      );
    };
    // Flutter framework 异常捕获
    FlutterError.onError = (FlutterErrorDetails details) {
      //获取 widget build 过程中出现的异常错误
      // reportErrorAndLog(details);
    };

    Widget _configApp() {
      return EasyLocalization(
        supportedLocales: [
          Locale('zh', 'CN'), // 簡體中文
          Locale('zh', 'HK'), // 繁體中文 Android
          // Locale('zh', "Hant_HK"), // 繁體中文_香港 iOS
          Locale('en', 'US'),
          // Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'),
        ],
        path: 'lib/resources/langs',
        fallbackLocale: Locale('en', 'US'),
        // assetLoader: CodegenLoader(),

        child: MyApp(),
      );
    }

    // 解决白屏问题 https://blog.csdn.net/lqw200931116/article/details/125420085
    //如果size是0，则设置回调，在回调中runApp
    if(window.physicalSize.isEmpty){
      print("window size is zero");
      window.onMetricsChanged = (){
        //在回调中，size仍然有可能是0
        if(!window.physicalSize.isEmpty){
          window.onMetricsChanged = null;
          print("window onMetricsChanged,run app");
          runApp(
              _configApp()
          );
        }
      };
    } else{
      //如果size非0，则直接runApp
      print("window load success,run app");
      runApp(
          _configApp()
      );
    }

  }, (error, stackTrace){   // 其他类型异常
    error.printError(info: '报错信息');
    stackTrace.printError(info: "报错信息");
  });



}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    /// 注册消息通知
    _initPlatformState();

  }

  @override
  Widget build(BuildContext context) {

    final language = LocalStorage.getLanguageValue();
    logs(language);
    var currentLocale = context.locale;
    if(language == 1) {  // 简中
      currentLocale = context.supportedLocales[0];
    }else if(language == 2) {  // 繁中
      currentLocale = context.supportedLocales[1];
    }else if(language == 3) {  // 英文
      currentLocale = context.supportedLocales[2];
    }else{  // 系统语言

      if(context.deviceLocale == context.supportedLocales[2]) { // 英语
        currentLocale = context.deviceLocale;
        LocalStorage.setLanguage(3);
      }else if(context.deviceLocale == context.supportedLocales[0]) {  // 简中
        currentLocale = context.deviceLocale;
        LocalStorage.setLanguage(1);
      }else if(context.deviceLocale.toString() == "zh_Hant_HK"   // 香港繁体
          || context.deviceLocale.toString() == "zh_Hant_TW"     // 台湾繁体
          || context.deviceLocale.toString() == "zh_Hant_CN"     // iOS繁体中文
          || context.deviceLocale.toString() == "zh_Hant_MO"     // 澳门繁体中文
          || context.deviceLocale.toString() == "zh_Hant_SG"     // 新加坡繁体中文
      ) {  // 繁體中文
        currentLocale = context.supportedLocales[1];
        LocalStorage.setLanguage(2);
      }else if(context.deviceLocale.toString() == "zh_Hans_CN") {  // iOS简体中文
        currentLocale = context.supportedLocales[0];
        LocalStorage.setLanguage(1);
        logs("${context.supportedLocales[1].toString()}");
      } else {  // 繁体中文, 英文
        currentLocale = context.supportedLocales[2];   //默认为繁体中文, 英文
        LocalStorage.setLanguage(3);
      }

    }

    logs("系統語言: ${context.deviceLocale.toString()}");
    logs(context.locale.toString());
    logs(currentLocale.toString());

    // 设置语言
    context.setLocale(currentLocale);

    final savedThemeMode = _getThemeMode();

    return AdaptiveTheme(
      light: ThemeData(
        brightness: Brightness.light,
        primarySwatch: createMaterialColor(Colors.white),

        primaryColor: Colors.white,
        scaffoldBackgroundColor: Colors.white,  // scaffold 组件下子组件的背景色

          colorScheme: ColorScheme(
            primary: Colors.white, // 顶部栏栏颜色
            primaryVariant: Colors.white,
            secondary: Colors.black,    // 月份选择器颜色
            background: Colors.white,
            error: Colors.red,
            brightness: Brightness.light,
            onBackground: Colors.pink,
            secondaryVariant: Colors.white,
            onError: Colors.yellow,
            onPrimary: Colors.black, //顶部栏字体颜色
            onSecondary: Colors.black,
            onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
            surface: Colors.white,  // 导航栏背景颜色
          ),
      ),
      dark: ThemeData(
        brightness: Brightness.dark, //MainCommon.darkBlueMaterialColor,  // createMaterialColor(Colors.black),
        backgroundColor: Colors.red,
        primaryColor: MainCommon.darkBlueMaterialColor,
        scaffoldBackgroundColor: Colors.black,  // scaffold 组件下子组件的背景色
        // primaryColorDark: Colors.green,
        // primaryColorLight: Colors.yellow,
        // colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.pink).copyWith(secondary: Colors.red),
        cardColor: MainCommon.darkBlueMaterialColor,  // card 组件子组件颜色
        dialogBackgroundColor: MainCommon.darkBlueMaterialColor,

        colorScheme: ColorScheme(
            primary: Colors.black, // 顶部栏栏颜色
            primaryVariant: Colors.white,
            secondary: Colors.white,    // 月份选择器颜色
            background: Colors.white,
            error: Colors.red,
            brightness: Brightness.dark,
            onBackground: Colors.pink,
            secondaryVariant: Colors.white,
            onError: Colors.yellow,
            onPrimary: Colors.blue, //顶部栏字体颜色
            onSecondary: Colors.black,
            onSurface: Colors.white,   // 导航栏字体颜色, 返回按钮颜色
            surface: MainCommon.darkBlueMaterialColor,  // 导航栏背景颜色
        )
      ),
      initial: AdaptiveThemeMode.light,
      builder: (ThemeData light, ThemeData dark) {
        return GetMaterialApp(
          getPages: LCRouter.routes,
          initialRoute: LCRouter.initialRoute,

          theme: light,
          // ThemeData(
          //   primarySwatch: MainCommon.homeThemeMaterialColor,
          // ),
          darkTheme: dark,
          // themeMode: ThemeMode.dark,

          // 本地化
          localizationsDelegates: context.localizationDelegates,
          supportedLocales: context.supportedLocales,
          locale: currentLocale,

          navigatorObservers: [FlutterSmartDialog.observer],
          builder: (BuildContext ctx, Widget? child) {
            return GestureDetector(   // 添加全局点击空白处下移键盘
              onTap: () {
                FocusScopeNode currentFocus = FocusScope.of(context);
                if (!currentFocus.hasPrimaryFocus &&
                    currentFocus.focusedChild != null) {
                  FocusManager.instance.primaryFocus?.unfocus();
                }
              },
              child: Material(
                type: MaterialType.transparency,
                child: FlutterSmartDialog(child: child,),
              ),
            );
          },

          // localizationsDelegates: [
          //   // MonthYearPickerLocalizations.delegate,
          // ],

        );
      },

    );


  }

  Future<AdaptiveThemeMode> _getThemeMode() async {
    final mode = await AdaptiveTheme.getThemeMode();
    return mode ?? AdaptiveThemeMode.light;
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> _initPlatformState() async {

    /// 注册监听
    FlutterPluginEngagelab.addEventHandler(
        onMTCommonReceiver: (Map<String, dynamic> message) async {
          FlutterPluginEngagelab.printMy("flutter onMTCommonReceiver: $message");
          String event_name = message["event_name"];
          String event_data = message["event_data"];
          FlutterPluginEngagelab.printMy("flutter onMTCommonReceiver event_name: " + event_name);
          FlutterPluginEngagelab.printMy("flutter onMTCommonReceiver event_data: " + event_data);
          setState(() {

            // debugLable = "flutter onMTCommonReceiver: $message";
            if (Comparable.compare(event_name, "onConnectStatus") == 0 ||
                Comparable.compare(event_name, "networkDidLogin") == 0) {
              if (Comparable.compare(event_data, "true") == 0) {
                FlutterPluginEngagelab.getRegistrationId().then((rid) {
                  FlutterPluginEngagelab.printMy("flutter get registration id : $rid");
                });
              }
            }
          });
        });

    /// 是否开启 Debug 模式, 发布版本需去掉
    FlutterPluginEngagelab.configDebugMode(true);

    if (Platform.isIOS) {
      FlutterPluginEngagelab.initIos(
        appKey: "21340fd3b5e4c6b74e38a35c",
        channel: "developer",
      );
    } else if (Platform.isAndroid) {
      FlutterPluginEngagelab.initAndroid();
    }


    /// 获取 RegistrationID
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    FlutterPluginEngagelab.getRegistrationId().then((rid) {
      FlutterPluginEngagelab.printMy("flutter get registration id : $rid");
      LocalStorage.setRegisterID(rid);
    });
    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

  }

}

